package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
    @Override
    public PageResult getItemList(PageResult pageResult){
        //判断查询结果(title字符串)是否有值
        boolean flag= StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<Item> queryWrapper=new QueryWrapper<>();
        //如果title有值，则对title进行模糊查询
        queryWrapper.like(flag,"title",pageResult.getQuery());
        //编辑MP的分页对象（页数/条数/总数/记录）    传递=页数/条数
        IPage<Item> page=new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        //返回值为IPage
        page=itemMapper.selectPage(page, queryWrapper);
        //获取搜索到的数据的总数和数据，并返回
        long total=page.getTotal();
        List<Item> rows=page.getRecords();
        return pageResult.setTotal(total).setRows(rows);
    }
    @Override
    @Transactional
    public void updateItemStatus(Item item){
        itemMapper.updateById(item);
    }
    @Override
    @Transactional
    public void deleteItemById(Integer id){
        itemMapper.deleteById(id);
    }
    @Override
    @Transactional
    public void updateItem(Item item){
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO){
        //ItemDesc.id=Item.id   所以ItemDesc的ID不能自增
        Item item=itemVO.getItem();
        ItemDesc itemDesc=itemVO.getItemDesc();
        //要求item入库后，动态返回ID！！！！
        //MP原则：入库后动态回显数据！！
        itemMapper.insert(item);
        //MybatisPlus数据自动回显
        itemDesc.setId(item.getId());
        //要求插入的商品详情id与商品id保持一致
        itemDescMapper.insert(itemDesc);
    }
}
